'use strict';
const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, DATE, TIME } = app.Sequelize;
  
  const Reservations = app.model.define(
    'Reservations',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      user_id: { type: INTEGER, allowNull: false },
      student_id: { type: INTEGER, allowNull: false },
      library_id: { type: INTEGER, allowNull: false },
      seat_id: { type: INTEGER, allowNull: false },
      reservation_date: { type: DATE, allowNull: false },
      start_time: { type: TIME, allowNull: false },
      end_time: { type: TIME, allowNull: false },
      check_in_time: { type: DATE },
      check_out_time: { type: DATE },
      status: { type: INTEGER, defaultValue: 0 },
      remark: { type: STRING(255) },
      create_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      update_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      }
    },
    {
      tableName: 'reservations',
      timestamps: true,
      createdAt: 'create_time',
      updatedAt: 'update_time'
    }
  );

  Reservations.associate = function() {
    app.model.Reservations.belongsTo(app.model.MiniProgramUsers, { foreignKey: 'user_id', targetKey: 'id', as: 'user' });
    app.model.Reservations.belongsTo(app.model.Students, { foreignKey: 'student_id', targetKey: 'id', as: 'student' });
    app.model.Reservations.belongsTo(app.model.Libraries, { foreignKey: 'library_id', targetKey: 'id', as: 'library' });
    app.model.Reservations.belongsTo(app.model.Seats, { foreignKey: 'seat_id', targetKey: 'id', as: 'seat' });
  };

  return Reservations;
};
